package com.example.financeapi.config.redis;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import java.io.IOException;

/**
 * redisson 配置，下面是单节点配置：
 * @author Alvin
 */
@Configuration
@EnableRedisHttpSession
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;

    /**
     *  解决redis集群环境没有开启Keyspace notifications导致的
     *  Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource
     * */
    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }

    @Bean
    public RedissonClient redissonClient() throws IOException {
        RedissonClient redisson=null;
        Config config =new Config();
        //单节点
        config.useSingleServer().setAddress("redis://"+host+":"+port);
        if(StringUtils.isEmpty(password)){
            config.useSingleServer().setPassword(null);
        }else{
            config.useSingleServer().setPassword(password);
        }
        config.useSingleServer().setTimeout(10000).setConnectTimeout(10000).setRetryInterval(5000);

        //添加主从配置
        //config.useMasterSlaveServers().setMasterAddress("").setPassword("").addSlaveAddress(new String[]{"",""});

        // 集群模式配置 setScanInterval()扫描间隔时间，单位是毫秒, //可以用"rediss://"来启用SSL连接
        // config.useClusterServers().setScanInterval(2000).addNodeAddress("redis://127.0.0.1:7000", "redis://127.0.0.1:7001").addNodeAddress("redis://127.0.0.1:7002");

        redisson =Redisson.create(config);
        System.out.println("redisson configuration："+ redisson.getConfig().toJSON());
        return redisson;
    }
}
